package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.listener.UploadListener;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController  //  @ResponseBody没有此注解,则return表示跳转到对应页面,有此注解则返回Jason字符串
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param employee 传入的employee对象
     * @param session  存储当前登录账户
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        //获取用户名与密码
        String password = employee.getPassword();
        String username = employee.getUsername();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //判断用户名是否存在
        //判断员工状态是否禁用
        //判断用户名密码是否正确
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, username).eq(Employee::getPassword, password);
        Employee emp = employeeService.getOne(lqw);

        if (emp == null) {//账户不存在
            return R.error("用户名或密码错误");
        }

        //账户存在,判断状态是否可用
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用!");
        }

        session.setAttribute("emp", emp.getId());
        return R.success(emp);
    }

    /**
     * 退出
     *
     * @param session 清空
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        //清空session
        session.removeAttribute("emp");
        return R.success("退出成功");
    }

    /**
     * 添加
     *
     * @param employee
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession session) {
        log.info("接收到员工信息{}", employee);
        //添加员工,设置默认密码,MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     *
     * @param page     当前页
     * @param pageSize 每页显示条数
     * @param name     姓名模糊查询
     * @return
     */
    @GetMapping("/page")
    public R<IPage<Employee>> page(int page, int pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);
        //分页
        Page page1 = new Page(page, pageSize);
        //条件&排序
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(page1, lqw);
        return R.success(page1);
    }

    /**
     * 修改
     *
     * @param session
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpSession session, @RequestBody Employee employee) {
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("查询错误");
    }

    @GetMapping("/download")
    public void download(){
        List<Employee> list = employeeService.list();
        EasyExcel.write("瑞吉外卖.xls", Employee.class).sheet("员工信息").doWrite(() -> {
            // 分页查询数据
            return list;
        });
        log.info("执行下载");
    }


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
    EasyExcel.read(file.getInputStream(),Employee.class,new UploadListener(employeeService)).sheet().doRead();
    return R.success("上传成功");
    }
}
